package top.linyuxb.lycloud.gateway.starter.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.linyuxb.lycloud.common.utils.LyRpcRibbonUtil;

import java.util.Objects;

/**
 * @author linyuxb
 * @date 2024/1/13 4:20 下午
 * @desc gateway客户端服务调整回调控制器
 */
@Slf4j
@RestController
@RequestMapping(value = "/lyGatewayClient")
public class LyGatewayClientController {

    @Value("${ly-config.user:}")
    private String user = StringUtils.EMPTY;
    @Value("${ly-config.user-password:}")
    private String userPassword = StringUtils.EMPTY;

    /**
     * 刷新客户端的服务缓存
     *
     * @param user
     * @param password
     * @return
     */
    @PostMapping(value = "/refreshServer")
    public String refreshServer(@RequestBody JSONObject req,
                                @RequestHeader(value = "user", defaultValue = "") String user,
                                @RequestHeader(value = "password", defaultValue = "") String password) {
        log.info("lyRpcClient refreshServer");
        if (!Objects.equals(this.user, user) || !Objects.equals(this.userPassword, password)) {
            return "接口请求非法！";
        }
        String app = req.getString("app");
        String env = req.getString("env");
        if(StrUtil.isAllNotBlank(app,env)){
            try {
                LyRpcRibbonUtil.cleanRegisterServer(app,env);
            } catch (Exception e) {
                log.error("LyConfigThread error", e);
            }
        }
        return "SUCCESS";
    }

}
